package com.batch.job;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;


// 主要学习熟悉JOB，Step之间的关系和概念(学习章节1.1)
// 学习当前Job，请将@SpringBootApplication 取消注释，并将其他Job的@SpringBootApplication 方法注释,否则会对当前结果产生干扰

//@SpringBootApplication
// EnableBatchProcessing 使spring创建springbatch操作相关类对象
@EnableBatchProcessing
public class HelloJob1 {

    // job启动器，本节用不上，后续会用
    @Autowired
    private JobLauncher jobLauncher;

    // Job构建工厂，用于构建Job对象
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    // Step构建工厂，用于构建 Step 对象
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    // 构建Tasklet
    @Bean
    public Tasklet tasklet1_01(){
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                System.out.println("hello world!   1_01");
                return RepeatStatus.FINISHED;
            }
        };

//        return (StepContribution contribution, ChunkContext chunkContext) -> {
//                System.out.println("hello world!");
//                return RepeatStatus.FINISHED;
//            };

    }
    @Bean
    public Tasklet tasklet1_02(){
        return (StepContribution contribution, ChunkContext chunkContext) -> {
                System.out.println("hello world02!  1_02");
                return RepeatStatus.FINISHED;
            };

    }

    // 构建Step
    @Bean
    public Step step1_01(){
        return stepBuilderFactory.get("step01").tasklet(tasklet1_01()).build();
    }

    @Bean
    public Step step1_02(){
        return stepBuilderFactory.get("step02").tasklet(tasklet1_02()).build();
    }
    // 构建Job
    @Bean
    public Job job1_01(){
        return jobBuilderFactory.get("hello-job01").start(step1_01()).next(step1_02()).build();
    }

    @Bean
    public Job job1_02(){
        return jobBuilderFactory.get("hello-job05").start(step1_01())
                .on("COMPLETED").to(step1_02())

                .end().build();
    }

    public static void main(String[] args) {
        SpringApplication.run(HelloJob1.class,args);
    }


}
